package com.hksj.acm.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.acm.vo.AirConditioningAlarmVO;
import com.hksj.acm.vo.ByDepartmentStatisticsAlarmExcelVO;
import com.hksj.acm.vo.ByFloorStatisticsAlarmExcelVO;
import com.hksj.acm.vo.FaultAlarmExcelVO;
import com.hksj.cbm.dto.AlarmDTO;
import com.hksj.cbm.dto.AlarmPageDTO;
import com.hksj.cbm.entity.SpecialityModel;
import com.hksj.cbm.service.AlarmService;
import com.hksj.cbm.service.SpecialityModelService;
import com.hksj.cbm.vo.AlarmRankingVO;
import com.hksj.cbm.vo.AlarmVO;
import com.hksj.cbm.vo.SpaceModelVO;
import com.hksj.common.core.common.Constants;
import com.hksj.common.core.common.SpecialityModelCodeEnum;
import com.hksj.common.core.util.EasyExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fjt
 * @data 2024/7/15 14:32
 * @describe 空调机组报警
 */
@Service
public class AirConditioningAlarmService {


    @Autowired
    private AlarmService alarmService;
    @Autowired
    private SpecialityModelService specialityModelService;


    /**
     * 报警记录分页查询
     * @param dto
     * @return
     */
    public Page<AirConditioningAlarmVO> pageAlarm(AlarmPageDTO dto){
        dto.setCode(SpecialityModelCodeEnum.air_conditioning.getCode());
        IPage<AlarmVO> page = alarmService.pageAlarm(dto);
        Page<AirConditioningAlarmVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<AlarmVO> list = page.getRecords();
        if (CollUtil.isEmpty(list)){
            return resultPage;
        }

        // 组装返回数据
        List<AirConditioningAlarmVO> voList = new ArrayList<>(list.size());
        list.forEach(alarmVO -> {
            AirConditioningAlarmVO vo = new AirConditioningAlarmVO();
            BeanUtils.copyProperties(alarmVO, vo);
            // 经产品确认设备位置只要楼栋和楼层两级
            List<SpaceModelVO> spaceModelVOList = alarmVO.getSpaceModelVOList();
            if (CollUtil.isNotEmpty(spaceModelVOList)){
                Map<String, String> spaceNameMap = spaceModelVOList.stream()
                        .collect(Collectors.toMap(p -> p.getSpaceItemValue(), p -> p.getModelName()));
                // 楼栋-楼层
                StringBuilder builder = new StringBuilder(spaceNameMap.get(Constants.FOUR_STR));
                if (StringUtils.isNotBlank(spaceNameMap.get(Constants.THREE_STR))){
                    builder.append("-").append(spaceNameMap.get(Constants.THREE_STR));
                }
                vo.setPathName(builder.toString());
            }
            voList.add(vo);
        });
        resultPage.setRecords(voList);
        return resultPage;
    }


    /**
     *  报警次数
     * @param dto
     * @return
     */
    public Integer total(AlarmPageDTO dto){
        dto.setCode(SpecialityModelCodeEnum.air_conditioning.getCode());
        return alarmService.total(dto);
    }


    /**
     * 报警记录排名(前10)
     * @param dto
     * @return
     */
    public List<AlarmRankingVO> ranking(AlarmPageDTO dto){
        dto.setCode(SpecialityModelCodeEnum.air_conditioning.getCode());
        return alarmService.ranking(dto);
    }


    /**
     * 报警记录导出
     * @param response
     * @param dto
     */
    public void exportList(HttpServletResponse response, AlarmDTO dto){
        dto.setCode(SpecialityModelCodeEnum.air_conditioning.getCode());
        List<AlarmVO> alarmList = alarmService.list(dto);
        // 1=设备报警记录
        if (Constants.ONE.equals(dto.getAlarmType())){
            LambdaQueryWrapper<SpecialityModel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SpecialityModel::getCode, SpecialityModelCodeEnum.air_conditioning.getCode());
            SpecialityModel specialityModel = specialityModelService.getOne(queryWrapper);
            if (ObjectUtil.isNull(specialityModel)){
                throw new RuntimeException("空调机组系统缺少专业模型配置信息");
            }
            String fileName = new StringBuffer().append("空调机组—设备报警记录")
                    .append(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).append(".xlsx").toString();

            // 统计方式(1=按楼层统计(此时没有科室) 2=按科室统计)
            Integer statisticalMethod = specialityModel.getStatisticalMethod();
            if (Constants.ONE.equals(statisticalMethod)){
                List<ByFloorStatisticsAlarmExcelVO> floorExcelList = new ArrayList<>();
                if (CollUtil.isNotEmpty(alarmList)){
                    for (AlarmVO vo : alarmList){
                        ByFloorStatisticsAlarmExcelVO excel = ByFloorStatisticsAlarmExcelVO.builder().deviceName(vo.getDeviceName())
                                .remark(vo.getRemark()).value(vo.getValue()).createTime(vo.getCreateTime()).build();

                        // 经产品确认设备位置只要楼栋和楼层两级
                        List<SpaceModelVO> spaceModelVOList = vo.getSpaceModelVOList();
                        if (CollUtil.isNotEmpty(spaceModelVOList)){
                            Map<String, String> spaceNameMap = spaceModelVOList.stream()
                                    .collect(Collectors.toMap(p -> p.getSpaceItemValue(), p -> p.getModelName()));
                            StringBuilder builder = new StringBuilder(spaceNameMap.get(Constants.FOUR_STR));
                            if (StringUtils.isNotBlank(spaceNameMap.get(Constants.THREE_STR))){
                                builder.append("-").append(spaceNameMap.get(Constants.THREE_STR));
                            }
                            excel.setPathName(builder.toString());
                        }
                        floorExcelList.add(excel);
                    }
                }
                EasyExcelUtil.exportExcelData(response, fileName, floorExcelList, ByFloorStatisticsAlarmExcelVO.class);
            }

            if (Constants.TWO.equals(statisticalMethod)){
                List<ByDepartmentStatisticsAlarmExcelVO> departmentExcelList = new ArrayList<>();
                if (CollUtil.isNotEmpty(alarmList)){
                    for (AlarmVO vo : alarmList){
                        ByDepartmentStatisticsAlarmExcelVO excel = ByDepartmentStatisticsAlarmExcelVO.builder().deviceName(vo.getDeviceName())
                                .departmentName(vo.getDepartmentName()).remark(vo.getRemark()).value(vo.getValue()).createTime(vo.getCreateTime()).build();

                        // 经产品确认设备位置只要楼栋和楼层两级
                        List<SpaceModelVO> spaceModelVOList = vo.getSpaceModelVOList();
                        if (CollUtil.isNotEmpty(spaceModelVOList)){
                            Map<String, String> spaceNameMap = spaceModelVOList.stream()
                                    .collect(Collectors.toMap(p -> p.getSpaceItemValue(), p -> p.getModelName()));
                            StringBuilder builder = new StringBuilder(spaceNameMap.get(Constants.FOUR_STR));
                            if (StringUtils.isNotBlank(spaceNameMap.get(Constants.THREE_STR))){
                                builder.append("-").append(spaceNameMap.get(Constants.THREE_STR));
                            }
                            excel.setPathName(builder.toString());
                        }
                        departmentExcelList.add(excel);
                    }
                }
                EasyExcelUtil.exportExcelData(response, fileName, departmentExcelList, ByDepartmentStatisticsAlarmExcelVO.class);
            }

        }

        // 2=机组故障记录
        if (Constants.TWO.equals(dto.getAlarmType())){
            List<FaultAlarmExcelVO> excelList = new ArrayList<>();
            if (CollUtil.isNotEmpty(alarmList)){
                for (AlarmVO vo : alarmList){
                    FaultAlarmExcelVO excel = FaultAlarmExcelVO.builder().deviceName(vo.getDeviceName())
                            .remark(vo.getRemark()).faultCode(vo.getFaultCode()).createTime(vo.getCreateTime()).build();
                    // 经产品确认设备位置只要楼栋和楼层两级
                    List<SpaceModelVO> spaceModelVOList = vo.getSpaceModelVOList();
                    if (CollUtil.isNotEmpty(spaceModelVOList)){
                        Map<String, String> spaceNameMap = spaceModelVOList.stream().
                                collect(Collectors.toMap(p -> p.getSpaceItemValue(), p -> p.getModelName()));
                        StringBuilder builder = new StringBuilder(spaceNameMap.get(Constants.FOUR_STR));
                        if (StringUtils.isNotBlank(spaceNameMap.get(Constants.THREE_STR))){
                            builder.append("-").append(spaceNameMap.get(Constants.THREE_STR));
                        }
                        excel.setPathName(builder.toString());
                    }
                    excelList.add(excel);
                }
            }
            String fileName = new StringBuffer().append("空调机组—机组故障记录")
                    .append(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).append(".xlsx").toString();
            EasyExcelUtil.exportExcelData(response, fileName, excelList, FaultAlarmExcelVO.class);
        }



    }




}
